package com.flynn.rock.crm.repository.customer;

import com.flynn.rock.crm.entity.customer.CustomerEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Repository
public interface CustomerRepository extends JpaRepository<CustomerEntity, Long>, JpaSpecificationExecutor<CustomerEntity> {

    @Transactional
    @Modifying
    @Query("update CustomerEntity as t set t.lastFollowUpTime = :followUpTime where t.customerId = :customerId")
    void updateLastFollowUpTime(@Param("customerId") Long customerId, @Param("followUpTime") LocalDateTime followUpTime);

    List<CustomerEntity> findAllByLastFollowUpTimeLessThanEqual(LocalDateTime dateTime);

    @Transactional
    @Modifying
    @Query("update CustomerEntity as t set t.followUpUserId  = null, t.followUpUserName = null where t.followUpUserId = :userId")
    void updateFollowUpUserNull(@Param("userId") Long userId);

    default Map<Long, CustomerEntity> listCustomer(Collection<Long> customerIds) {
        return this.findAllById(customerIds).stream()
                .collect(Collectors.toMap(CustomerEntity::getCustomerId, O -> O, (O1, O2) -> O2));
    }
}
